package com.kitkat.aop;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.kitkat.annotation.UserTokenCheck;
import com.kitkat.dao.AbstractTokenDAO;
import com.kitkat.entities.UserToken;
import com.kitkat.util.CodeAndMessage;

@Aspect
@Component
public class UserTokenCheckAOP {
	@Autowired
	private AbstractTokenDAO<String, UserToken> userTokenDAO;
	
	@Pointcut(value="execution(public java.util.Map<String,Object> com.kitkat.serviceImpl.*.*(..))&&@annotation(utc)")
	public void pointcut(UserTokenCheck utc){}
	
	@Around(value="pointcut(utc)")
	public Map<String,Object> checkUserToken(ProceedingJoinPoint joinPoint,UserTokenCheck utc) throws Throwable{
		Map<String,Object> hm = new HashMap<String,Object>();
		String token = null;
		UserToken userToken = null;
		if(utc.tokenIndex()>=0){
			Object[] args = joinPoint.getArgs();
			token = (String)args[utc.tokenIndex()];
			userToken = this.userTokenDAO.get(token);
			
			if(userToken==null){
				hm.put("code", CodeAndMessage.NoTokenCode);
				hm.put("message", CodeAndMessage.NoTokenMessage);
				hm.put("result", null);
				return hm;
			}
		}
		
		hm = (Map<String, Object>) joinPoint.proceed();
		
		if(hm.get("message").equals(CodeAndMessage.SuccessMessage)){
			userToken.setLastModifyDate(new Date());
			this.userTokenDAO.set(token, userToken);
		}
		return hm;
	}
}
